package com.css.fxfzcpxx.modules.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @Author: xzy
 * @CreateTime: 2023/11/28 12:01
 * @Description: WebSocket处理器
 */
@Component
@Slf4j
public class DataStatusHandler extends TextWebSocketHandler {

    private final WebSocketManager webSocketManager;

    @Autowired
    public DataStatusHandler(WebSocketManager webSocketManager) {
        this.webSocketManager = webSocketManager;
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //super.handleTransportError(session, exception);

        if (session.isOpen()) {
            session.close();
        }
    }



    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WebSocket连接已建立");

        // 将新建立的会话添加到WebSocket管理器中
        webSocketManager.addSession(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 在连接关闭时从WebSocket管理器中移除会话
        webSocketManager.removeSession(session);

        log.info("WebSocket连接已关闭");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        // 解析接收到的消息
        ObjectMapper objectMapper = new ObjectMapper();
        String payload1 = message.getPayload();


        //DataStatusMessage statusMessage = updateDataStatus(dataId, status, interfaceType);


        // 将消息转为JSON格式
        String jsonMessage = objectMapper.writeValueAsString(payload1);

        // 向所有客户端发送消息
        for (WebSocketSession webSocketSession : webSocketManager.getSessions()) {
            webSocketSession.sendMessage(new TextMessage(jsonMessage));
            log.info(webSocketSession.getId() + "," + " : " + message.getPayload());
        }
    }
}
